package com.imflea.zero.service.cms.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.imflea.zero.util.ZeroCacheUtils;
import com.imflea.zero.util.base.CommonUtils;
import com.imflea.zero.constant.MallPromptContant;
import com.imflea.zero.exception.BizException;
import com.imflea.zero.model.dao.cms.CmsTemplateMapper;
import com.imflea.zero.model.entity.cms.CmsContentInfo;
import com.imflea.zero.model.entity.cms.CmsTemplate;
import com.imflea.zero.model.entity.cms.dto.CmsTemplateDto;
import com.imflea.zero.model.entity.cms.vo.CmsContentVo;
import com.imflea.zero.service.cms.ICmsContentInfoService;
import com.imflea.zero.service.cms.ICmsTemplateService;
import com.imflea.zero.utils.AssertUtil;
import com.imflea.zero.utils.RestUtil;
import com.imflea.zero.utils.SessionUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 发布模板信息 服务实现类
 * </p>
 *
 * @author xiangbaoyu
 * @since 2021-09-17
 */
@Service
public class CmsTemplateServiceImpl extends ServiceImpl<CmsTemplateMapper, CmsTemplate> implements ICmsTemplateService {

    private static final String LIST_PREFIX = "Map:YWB:CMS_CONTENT_INFO:";
    private static final String ID_PREFIX = "Map:YWB:CMS_CONTENT_INFO:ID:";

    private static final String NOT_FOUND = "未找到有效的内容";

    @Autowired
    private ICmsContentInfoService iCmsContentInfoService;

    @Override
    public CmsTemplate saveEntity(CmsTemplate entity) {

        entity.setId(CommonUtils.generateRandomString());
        entity.setTenantId(SessionUtils.getTenantId());

        fillContent(entity);

        boolean success = this.save(entity);
        if (success) {
            success = iCmsContentInfoService.saveBatch(entity.getContentInfoList());
        }

        return RestUtil.orElseThrow(success, entity, MallPromptContant.CMS_TEMPLATE_SAVE_FAIL);
    }


    @Override
    public CmsTemplate updateEntity(CmsTemplate entity) {

        String templateId = entity.getId();
        AssertUtil.mustNotEmpty(templateId, MallPromptContant.ID_NOT_EMPTY);

        boolean success = this.updateById(entity);
        // 获取数据库的正文列表
        List<CmsContentInfo> oldList = iCmsContentInfoService.queryListByTemplateId(templateId);
        // 前端传过来待保存的正文列表
        List<CmsContentInfo> contentInfoList = entity.getContentInfoList();

        List<String> idList = deleteIds(oldList, contentInfoList);
        if (!CommonUtils.isNull(idList)) {
            success = iCmsContentInfoService.removeByIds(idList);
        }

        if (!CommonUtils.isNull(contentInfoList)) {
            fillBaseInfo(templateId, contentInfoList);
            success = iCmsContentInfoService.saveOrUpdateBatch(contentInfoList);
        }

        return RestUtil.orElseThrow(success, entity, MallPromptContant.CMS_TEMPLATE_UPDATE_FAIL);
    }

    @Override
    public Boolean removeEntity(String id) {

        AssertUtil.mustNotEmpty(id, MallPromptContant.ID_NOT_EMPTY);

        Boolean success = iCmsContentInfoService.removeByTemplateId(id);
        if (success) {
            success = this.removeById(id);
        }
        return RestUtil.orElseThrow(success, MallPromptContant.CMS_TEMPLATE_REMOVE_FAIL);
    }

    @Override
    public CmsTemplate queryEntity(String id) {

        AssertUtil.mustNotEmpty(id, MallPromptContant.ID_NOT_EMPTY);

        CmsTemplate template = this.getById(id);
        if (!CommonUtils.isNull(template)) {
            List<CmsContentInfo> list = iCmsContentInfoService.queryListByTemplateId(id);
            template.setContentInfoList(list);
        }

        return template;
    }

    @Override
    public PageInfo<CmsTemplate> queryPage(CmsTemplateDto dto) {

        LambdaQueryWrapper<CmsTemplate> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.eq(CmsTemplate::getTenantId, SessionUtils.getTenantId());

        String publishType = dto.getPublishType();
        lambdaQuery.eq(!CommonUtils.isNull(publishType), CmsTemplate::getPublishType, publishType);

        String contentType = dto.getContentType();
        lambdaQuery.eq(!CommonUtils.isNull(contentType), CmsTemplate::getContentType, contentType);

        String title = dto.getTitle();
        lambdaQuery.like(!CommonUtils.isNull(title), CmsTemplate::getTitle, title);

        LocalDateTime publishTimeStart = dto.getPublishTimeStart();
        LocalDateTime publishTimeEnd = dto.getPublishTimeEnd();
        if (!CommonUtils.isNull(publishTimeStart) && !CommonUtils.isNull(publishTimeEnd)) {
            lambdaQuery.between(CmsTemplate::getPublishTime, publishTimeStart, publishTimeEnd);
        }

        Integer pageIndex = dto.getPageNum();
        Integer pageSize = dto.getPageSize();
        PageHelper.startPage(pageIndex, pageSize);
        List<CmsTemplate> adoptInfos = this.list(lambdaQuery);
        PageInfo<CmsTemplate> pageResult = new PageInfo<>(adoptInfos);
        return pageResult;
    }

    /*
        查询一条发布信息

        在小程序端查询发布信息时,会根据发布类型,内容类型,作用域信息
         找到符合条件的一条记录,
     */
    @Override
    public CmsContentVo queryOneFromRedis(CmsTemplateDto dto) {

        String publishType = dto.getPublishType();
        String contentType = dto.getContentType();

        AssertUtil.mustNotEmpty(publishType, "发布类型不能为空");
        AssertUtil.mustNotEmpty(contentType, "内容类型不能为空");

        String scope = dto.getScope();
        if (CommonUtils.isNull(scope)) {
            scope = "cms_all";
        }

        try {
            String redisKey = LIST_PREFIX + publishType + ":" + contentType + ":" + scope;
            String json = ZeroCacheUtils.getString(redisKey);

            if (!CommonUtils.isNull(json)) {
                return JSONUtil.toBean(json, CmsContentVo.class);
            }

            List<CmsContentVo> contentVoList = this.baseMapper.seleContent(publishType, contentType, scope);
            if (CommonUtils.isNull(contentVoList)) {
                return null;
//                throw new BizException(NOT_FOUND);
            }
            CmsContentVo cmsContentVo = contentVoList.get(0);

            ZeroCacheUtils.setString(redisKey, JSONUtil.toJsonStr(cmsContentVo));
            ZeroCacheUtils.expire(redisKey, 150);

            return cmsContentVo;
        } catch (Exception e) {
            log.error("error:{}", e);
            throw new BizException(e);
        }
    }

    /*
        查询TOPN条发布信息

        在小程序端查询发布信息时,会根据发布类型,内容类型,作用域信息
         找到符合条件的多条记录,
     */
    @Override
    public List<CmsContentVo> queryListFromRedis(CmsTemplateDto dto) {

        String publishType = dto.getPublishType();
        String contentType = dto.getContentType();

        AssertUtil.mustNotEmpty(publishType, "发布类型不能为空");
        AssertUtil.mustNotEmpty(contentType, "内容类型不能为空");

        Integer topN = dto.getTopN();
        if (CommonUtils.isNull(topN)) {
            topN = 1;
        }

        String scope = dto.getScope();
        if (CommonUtils.isNull(scope)) {
            scope = "cms_all";
        }

        try {
            String redisKey = LIST_PREFIX + publishType + ":" + contentType + ":" + scope + ":" + topN;
            String json = ZeroCacheUtils.getString(redisKey);
            if (!CommonUtils.isNull(json)) {
                return JSONUtil.toList(json, CmsContentVo.class);
            }

            List<CmsContentVo> list = this.baseMapper.seleContent(publishType, contentType, scope);
            if (CommonUtils.isNull(list)) {
                throw new BizException(NOT_FOUND);
            }
            if (list.size() > topN) {
                list = list.subList(0, topN);
            }

            ZeroCacheUtils.setString(redisKey, JSONUtil.toJsonStr(list));
            ZeroCacheUtils.expire(redisKey, 150);

            return list;
        } catch (Exception e) {
            log.error("error:{}", e);
            throw new BizException(e);
        }
    }

    @Override
    public List<CmsTemplate> queryList(CmsTemplateDto cmsTemplateDto) {

        LambdaQueryWrapper<CmsTemplate> lambdaQuery = Wrappers.lambdaQuery();
        String title = cmsTemplateDto.getTitle();
        lambdaQuery.like(!CommonUtils.isNull(title), CmsTemplate::getTitle, title);
        List<CmsTemplate> list = this.list(lambdaQuery);
        return RestUtil.orEmptyList(list);
    }

    @Override
    public CmsContentVo queryContentFromRedis(CmsTemplateDto dto) {

        String id = dto.getId();
        AssertUtil.mustNotEmpty(id, MallPromptContant.ID_NOT_EMPTY);

        try {

            String redisKey = ID_PREFIX + id;
            String json = ZeroCacheUtils.getString(redisKey);
            if (!CommonUtils.isNull(json)) {

                CmsContentVo contentVo = JSONUtil.toBean(json, CmsContentVo.class);
                if (!CommonUtils.isNull(contentVo)) {
                    return contentVo;
                }
            }

            List<CmsContentVo> contentVoList = this.baseMapper.selectContent(id);
            if (CommonUtils.isNull(contentVoList)) {
                throw new BizException(NOT_FOUND);
            }

            CmsContentVo result = aggregationContent(contentVoList);

            ZeroCacheUtils.setString(redisKey, JSONUtil.toJsonStr(result));
            ZeroCacheUtils.expire(redisKey, 60);

            return result;
        } catch (Exception e) {
            log.error("error:{}", e);
            throw new BizException(e);
        }

    }

    private CmsContentVo aggregationContent(List<CmsContentVo> contentVoList) {

        CmsContentVo result = contentVoList.get(0);
        List<String> contents = contentVoList.stream()
                .map(CmsContentVo::getContent)
                .collect(Collectors.toList());
        result.setContents(contents);
        return result;
    }

    // 填充正文信息
    private void fillContent(CmsTemplate entity) {

        List<CmsContentInfo> contentInfoList = entity.getContentInfoList();
        if (CommonUtils.isNull(contentInfoList)) {
            throw new BizException("缺少正文信息");
        }

        String templateId = entity.getId();
        contentInfoList.forEach(contentInfo -> {
            contentInfo.setId(CommonUtils.generateRandomString());
            contentInfo.setTenantId(SessionUtils.getTenantId());
            contentInfo.setTemplateId(templateId);

            RestUtil.settingCreator(contentInfo);
            RestUtil.settingUpdator(contentInfo);
//            contentInfo.setCreateUserId(SessionUtils.getUserId());
//            contentInfo.setCreateUserName(SessionUtils.getUserName());
//            contentInfo.setCreateTime(LocalDateTime.now());
//
//            contentInfo.setUpdateUserId(SessionUtils.getUserId());
//            contentInfo.setUpdateUserName(SessionUtils.getUserName());
//            contentInfo.setUpdateTime(LocalDateTime.now());
        });
    }

    // 比对两个集合差集为待删除的元素
    private List<String> deleteIds(List<CmsContentInfo> oldList, List<CmsContentInfo> contentInfoList) {

        oldList.removeAll(contentInfoList);
        List<String> idList = oldList.stream()
                .map(CmsContentInfo::getId)
                .collect(Collectors.toList());
        return idList;
    }

    // 填充基本信息
    private void fillBaseInfo(String templateId, List<CmsContentInfo> contentInfoList) {

        contentInfoList.forEach(contentInfo -> {
            String id = contentInfo.getId();

            if (CommonUtils.isNull(id)) {
                // NOTE 本次新增了正文项
                contentInfo.setId(CommonUtils.generateRandomString());
                contentInfo.setTemplateId(templateId);
                contentInfo.setTenantId(SessionUtils.getTenantId());
                RestUtil.settingCreator(contentInfo);
//                    contentInfo.setCreateUserId(SessionUtils.getUserId());
//                    contentInfo.setCreateUserName(SessionUtils.getUserName());
//                    contentInfo.setCreateTime(LocalDateTime.now());

            }
            // NOTE 本次修改了正文项
            RestUtil.settingUpdator(contentInfo);
//                contentInfo.setUpdateUserId(SessionUtils.getUserId());
//                contentInfo.setUpdateUserName(SessionUtils.getUserName());
//                contentInfo.setUpdateTime(LocalDateTime.now());
        });
    }


}
